package netty.server;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.DatagramPacket;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.Random;

@Slf4j
public class UdpServerHandler extends SimpleChannelInboundHandler<DatagramPacket> {

    private static final Random random = new Random();

    private static final String[] quotes = {
            "道可道，非常道；名可名，非常名。",
            "无名天地之始，有名万物之母。",
            "故常无，欲以观其妙；常有，欲以观其徼。",
            "此两者同出而异名，同谓之玄。",
            "玄之又玄，众妙之门。",
    };

    public UdpServerHandler() {
        log.info(">>> init {}", this.toString());
    }

    private static String nextQuote() {
        int quoteId;
        synchronized (random) {
            quoteId = random.nextInt(quotes.length);
        }
        return quotes[quoteId];
    }

    @Override
    public void channelRead0(ChannelHandlerContext ctx, DatagramPacket packet) throws Exception {
        try {
            // discard
            // Do something with msg
            log.info("receive data: {}, {}", packet, ctx.channel().remoteAddress());

            if ("QOTM?".equals(packet.content().toString(CharsetUtil.UTF_8))) {
                ctx.writeAndFlush(new DatagramPacket(
                        Unpooled.copiedBuffer("QOTM: " + nextQuote(), CharsetUtil.UTF_8), packet.sender()));
            }


        } finally {
//            ReferenceCountUtil.release(msg);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        // Close the connection when an exception is raised.
        cause.printStackTrace();
        ctx.close();
    }
}